package org.algorithm.熊猫.数组.三月.第四周;

/**
 * @author zhx
 * @version 1.0
 * @date 2022/03/24 8:35 PM
 * @description: 周六
 * <p>
 * url:  https://leetcode-cn.com/problems/search-rotate-array-lcci/
 */
public class 搜索旋转数组 {

    public static void main(String[] args) {
        int[] arr = {15, 16, 19, 20, 25, 1, 3, 4, 5, 7, 10, 14};
        System.out.println(search(arr, 5));
    }


    public static int search(int[] arr, int target) {
        int length = arr.length;
        if (length == 0) {
            return -1;
        }
        if (arr[0] == target) {
            return 0;
        }
        int l = 0;
        int r = length - 1;
        int mid;

        while (l <= r) {
            mid = l + (r - l) / 2;
            //在中间
            if (arr[mid] == target) {
                //继续向左判断，是否前置有重复的
                while (mid > 0 && arr[mid - 1] == target) {
                    mid--;
                }
                return mid;
            }

            if (arr[mid] < arr[r]) {
                if (arr[mid] < target && target <= arr[r]) {
                    l = mid + 1;
                } else {
                    r = mid - 1;
                }
            } else if (arr[mid] > arr[r]) {
                if (arr[l] <= target && target < arr[mid]) {
                    r = mid - 1;
                } else {
                    l = mid + 1;
                }
            } else {
                r--;
            }
        }
        return -1;
    }
}
